import { defineStore } from 'pinia'
import type { userType } from '../../types/user'
import { useRegister } from '@/service/login/login'
import { upLoadFile, changeUserInformation } from '@/service/user/user'
import { base64toFile } from '@/utils/filetype-change'
import { ElMessage } from 'element-plus'

const useUserStore = defineStore('user', {
  state: (): userType => ({
    userMessage: {
      userId: '',
      userBust: '',
      userVita: '',
      nickname: '',
      username: '',
      password: '',
      userEmail: '',
      phoneNumber: '',
      skill: '',
      score: 0,
      age: 0,
      sex: ''
    },
    bustTemp: '',
    fileType: ''
  }),

  actions: {
    async userLogin(formData: any) {
      if (this.bustTemp != '') {
        const file = base64toFile(this.bustTemp, this.userMessage.nickname + '.' + this.fileType)
        const fileData = new FormData()
        fileData.append('file', file)
        fileData.append('fileType', this.fileType)
        const res: any = await upLoadFile(fileData)
        formData.userBust = res.data
      } else {
        const fileData = new FormData()
        fileData.append('file', '')
        const res: any = await upLoadFile(fileData)
        formData.userBust = res.data
      }
      useRegister(formData).then((res: any) => {
        if (res.code == 0) {
          ElMessage.error('账户已存在，请重新注册！')
        } else {
          ElMessage({
            message: '注册成功！',
            type: 'success'
          })
          location.reload()
        }
      })
    },
    async updateUserInformation(formData: any) {
      let userBustUrl = this.userMessage.userBust // 默认使用旧头像URL
      // 如果有新头像（bustTemp不为空），先上传新头像
      if (this.bustTemp !== '') {
        try {
          const file = base64toFile(this.bustTemp, this.userMessage.nickname + '.' + this.fileType)
          const fileData = new FormData()
          fileData.append('file', file)
          const uploadResult: any = await upLoadFile(fileData)
          userBustUrl = uploadResult.data // 获取新上传头像的URL
        } catch (error) {
          console.error('头像上传失败:', error)
          return
        }
      }
      const updatedInfo = { ...formData, userBust: userBustUrl }
      console.log('更新信息:', updatedInfo)
      if (userBustUrl !== undefined) {
        await changeUserInformation(updatedInfo)
        this.$patch({ userMessage: { ...this.userMessage, ...updatedInfo } })
      } else {
        console.error('上传信息失败')
      }
    },
    userDataInit(data: any) {
      this.$patch({
        userMessage: data
      })
    }
  },
  //持久化
  persist: true
})

export default useUserStore
